var Povertypolicyledger = function() {

    // HTML模板
    // 享受政策
    var policyGroupTemp = stringLines(function(){/*
	<div class="policy-div" style="margin-top: 20px;">
        <div class="row">
            <div class="col-md-4">
                <select class="form-control" name="policyType">
                    <option value="0">请选择</option>
                    <option value="1">教育扶贫</option>
                    <option value="2">健康扶贫</option>
                    <option value="3">农村低保</option>
                    <option value="4">就业补助</option>
                    <option value="5">危房改造</option>
                    <option value="6">雨露计划</option>
                    <option value="7">农村五保</option>
                    <option value="8">临时救助</option>
                    <option value="9">残疾补贴</option>
                    <option value="10">小额信贷</option>
                    <option value="11">就业奖补</option>
                    <option value="12">计生奖补</option>
                    <option value="13">金融扶贫</option>
                    <option value="14">救灾款</option>
                    <option value="15">其他</option>
                </select>
            </div>
            <div class="col-md-1">
                <button type="button" class="btn btn-danger remove-policy"><i class="fa fa-close"></i></button>
            </div>
        </div>
        <div class="row policySpec-div" style="margin-top: 10px;">
            <div class="col-md-3">
                <select class="form-control spec-type" name="specType">
                    <option value="1">分季</option>
                    <option value="2">分月</option>
                    <option value="0">无</option>
                </select>
            </div>
            <div class="col-md-3 quarter-div">
                <select class="form-control quarter" name="quarter">
                    <option value="1">春季</option>
                    <option value="2">夏季</option>
                    <option value="3">秋季</option>
                    <option value="4">冬季</option>
                </select>
            </div>
            <div class="col-md-3 month-div hide">
                <select class="form-control month" name="month">
                    <option value="1">1月</option>
                    <option value="2">2月</option>
                    <option value="3">3月</option>
                    <option value="4">4月</option>
                    <option value="5">5月</option>
                    <option value="6">6月</option>
                    <option value="7">7月</option>
                    <option value="8">8月</option>
                    <option value="9">9月</option>
                    <option value="10">10月</option>
                    <option value="11">11月</option>
                    <option value="12">12月</option>
                </select>
            </div>
            <div class="col-md-3">
                <select class="form-control explain" name="explain">
                    <option value="1">金额补助</option>
                    <option value="2">其他说明</option>
                </select>
            </div>
            <div class="col-md-1">
                <button type="button" class="btn btn-success addPolicySpec-btn"><i class="fa fa-plus"></i></button>
            </div>
        </div>
    </div>
*/});

    // 享受政策规格
    var policySpecTemp = stringLines(function(){/*
    <div class="row policySpec-div" style="margin-top: 10px;">
        <div class="col-md-3">
            <select class="form-control spec-type" name="specType">
                <option value="1">分季</option>
                <option value="2">分月</option>
                <option value="0">无</option>
            </select>
        </div>
        <div class="col-md-3 quarter-div">
            <select class="form-control quarter" name="quarter">
                <option value="1">春季</option>
                <option value="2">夏季</option>
                <option value="3">秋季</option>
                <option value="4">冬季</option>
            </select>
        </div>
        <div class="col-md-3 month-div hide">
            <select class="form-control month" name="month">
                <option value="1">1月</option>
                <option value="2">2月</option>
                <option value="3">3月</option>
                <option value="4">4月</option>
                <option value="5">5月</option>
                <option value="6">6月</option>
                <option value="7">7月</option>
                <option value="8">8月</option>
                <option value="9">9月</option>
                <option value="10">10月</option>
                <option value="11">11月</option>
                <option value="12">12月</option>
            </select>
        </div>
        <div class="col-md-3">
            <select class="form-control explain" name="explain">
                <option value="1">金额补助</option>
                <option value="2">其他说明</option>
            </select>
        </div>
        <div class="col-md-1">
            <button type="button" class="btn btn-danger removePolicySpec-btn"><i class="fa fa-minus"></i></button>
        </div>
    </div>
*/});


    var datalist_url = $('.datalist_url').val();
    var edit_url = $('.edit_url').val();
    var delete_url = $('.delete_url').val();
    var redirect_url = $('.redirect_url').val();
    var save_url = $('.save_url').val();

    var detailData_url = $('.detailData_url').val();


    // Datepicker
    var init_datepicker = function () {
        if($('.date-year').length > 0){
            $('.date-year').datepicker({
                language:"cn",
                format: 'yyyy',
                todayBtn : "linked",
                autoclose : true,
                startView : 2,
                maxViewMode : 2,
                minViewMode : 2,
                todayHighlight : true,
                endDate : new Date()
            });
        }
    };

    var initTable = function() {
        var table = $('#data-table');

        if(table.length > 0){
            table.dataTable({
                "processing": true,
                "ordering": false, // 禁止排序
                serverSide: true,// 开启服务器模式
                "ajax": {
                    url: datalist_url,
                },
                "autoWidth": false,
                "columns": [
                    {"data": "villageName"},
                    {"data": "year"},
                    {"data": "countPovertypolicy"},
                    {"data": "countFamily"},
                    {"data": "countPeople"},
                    {"data": "totalAmount"},
                    {
                        //"width": "15%",
                        "data": "null",
                        "render": function(data, type, row, meta) {
                            var html = '<a href="'+detailData_url+'?ledgerId='+row.id+'" type="button" class="btn btn-info">明细</a>';
                            html += '<a href="'+edit_url+'?id='+row.id+'" type="button" class="btn btn-success">编辑</a>';
                            html += '<button type="button" class="btn btn-danger delete-btn">删除</button>';

                            return html;
                        }
                    }
                ],
                "language": {
                    url: '/public/static/admin/pages/datatable_cn.json'
                },
                "lengthMenu": [[10, 20, 50, 100, 150], [10, 20, 50, 100, 150]],
                "pageLength": 10,
                "scrollX":"",
                "destroy": false,
                "stateSave": true,
                "stateSaveParams": function (settings, data) {
                    var search = data.search.search;
                    if(search){
                        var arr = $.parseJSON(search);
                        for(var key in arr){
                            $("#searchForm input[name='"+key+"']").val(arr[key]);
                            $("#searchForm select[name='"+key+"']").val(arr[key]);
                        }
                    }
                },
                "order": [
                    [4, "asc"]
                ],
                "columnDefs": [{
                    "orderable": false,
                    "targets": [0, 5]
                }],
                "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'relative'<'col-md-5'i><'col-md-7'>lp>",
                "fnInitComplete": function() {
                    //var nTrs = table.fnGetNodes();//fnGetNodes获取表格所有行，nTrs[i]表示第i行tr对象
                    var city = $('input[name=city]').val();
                    if(city){
                        //$("#city").find("option:contains('"+city+"')").attr("selected", true);
                        get_xian($("#city"));
                    }
                }
            });
        }

        // 筛选
        $('#doSearch').on('click', function(event){
            var param = $('#searchForm').serializeObject();

            tableSearch(table, param);
        });

        // 删除
        table.on('click', '.delete-btn', function(event) {
            // 操作行对象
            var dataArr = table.DataTable().rows($(this).parents("tr")).data();
            var id = dataArr[0].id;
            var _this = $(this);

            var text = '是否要删除这条数据？';
            var title = '请确认';
            var confirmBtn = '确定';
            var cancelBtn = '取消';
            event.preventDefault();

            layer.confirm(
                text,
                {
                    title: title,
                    btn: [confirmBtn, cancelBtn]
                },
                function(index){
                    layer.close(index);
                    var url = delete_url;
                    var data = {'id':id};
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: data,
                        dataType : 'json',
                        success: function (data) {
                            layer.msg(data.msg);
                            if(data.code == 1){
                                _this.parents('tr').remove();
                            }
                        }
                    });
                }
            );
        });
    };

    var tableSearch = function(table, params) {

        table.DataTable().search(JSON.stringify(params)).draw();
    };

    // 详情页初始化
    var initDetail = function() {
        if($('#ajax-form').length > 0){
            init_specType();
            handlePolicySpec();
        }
    };

    // 初始化 享受政策规格类型
    var init_specType = function($obj) {
        if ($obj) {
            var specType = $obj.val();
            switch(specType){
                case '0':
                    // 不能用 ‘style="display: none;"’ ，因为元素消失了，导致数组长度对应不上
                    /*$obj.parents('.policySpec-div').find('.quarter-div').hide();
                    $obj.parents('.policySpec-div').find('.month-div').hide();*/
                    $obj.parents('.policySpec-div').find('.quarter-div').addClass('hide');
                    $obj.parents('.policySpec-div').find('.month-div').addClass('hide');
                    break;
                case '1':
                    /*$obj.parents('.policySpec-div').find('.quarter-div').show();
                    $obj.parents('.policySpec-div').find('.month-div').hide();*/
                    $obj.parents('.policySpec-div').find('.quarter-div').removeClass('hide');
                    $obj.parents('.policySpec-div').find('.month-div').addClass('hide');
                    break;
                case '2':
                    /*$obj.parents('.policySpec-div').find('.quarter-div').hide();
                    $obj.parents('.policySpec-div').find('.month-div').show();*/
                    $obj.parents('.policySpec-div').find('.quarter-div').addClass('hide');
                    $obj.parents('.policySpec-div').find('.month-div').removeClass('hide');
                    break;
                default: break;
            }
        } else {
            $('.policy-div').each(function(){
                $(this).find('.spec-type').each(function(){
                    var $obj = $(this);
                    var specType = $obj.val();
                    switch(specType){
                        case '0':
                            $obj.parents('.policySpec-div').find('.quarter-div').addClass('hide');
                            $obj.parents('.policySpec-div').find('.month-div').addClass('hide');
                            break;
                        case '1':
                            $obj.parents('.policySpec-div').find('.quarter-div').removeClass('hide');
                            $obj.parents('.policySpec-div').find('.month-div').addClass('hide');
                            break;
                        case '2':
                            $obj.parents('.policySpec-div').find('.quarter-div').addClass('hide');
                            $obj.parents('.policySpec-div').find('.month-div').removeClass('hide');
                            break;
                        default: break;
                    }
                });
            });
        }
    };

    // 享受政策规格
    var handlePolicySpec = function() {
        $('#policy-group').find('.policy-div').each(function (i) {
            $(this).find('.policySpec-div').each(function(j){
                // $(this).find('select[name^=specType]').attr('name', 'specType_'+i);
                // $(this).find('select[name^=quarter]').attr('name', 'quarter_'+i);
                // $(this).find('select[name^=month]').attr('name', 'month_'+i);
                // $(this).find('select[name^=explain]').attr('name', 'explain_'+i);
                $(this).find('select.spec-type').attr('name', 'specType_'+i);
                $(this).find('select.quarter').attr('name', 'quarter_'+i);
                $(this).find('select.month').attr('name', 'month_'+i);
                $(this).find('select.explain').attr('name', 'explain_'+i);
            });
        });
    };

    // 检查享受政策规格
    var checkPolicySpec = function() {
        var isChecked = true;
        $('#policy-group').find('.policy-div').each(function (i) {
            if($(this).find('.policySpec-div').length > 1){
                var spec_type1 = $(this).find('.spec-type').first().val();
                var quarter1 = $(this).find('.quarter-div').first().find('select').val();
                var month1 = $(this).find('.month-div').first().find('select').val();
                $(this).find('.policySpec-div').each(function(j){
                    //console.log(j);
                    var spec_type = $(this).find('.spec-type').val();
                    // 选项要一致
                    if(spec_type1 != spec_type){
                        isChecked = false;
                        return;
                    }
                    if (spec_type == 1) {
                        var quarter = $(this).find('.quarter-div').first().find('select').val();
                        // 季度不能重复
                        if(j > 0 && quarter1 == quarter){
                            isChecked = false;
                            return;
                        }
                    } else {
                        // 月份不能重复
                        var month = $(this).find('.month-div').first().find('select').val();
                        if(j > 0 && month1 == month){
                            isChecked = false;
                            return;
                        }
                    }
                });
            }
        });

        return isChecked;
    };


    return {
        init: function() {
            init_datepicker();
            initTable();
            initDetail();

            this.onEvent();
        },

        onEvent: function() {

            // 添加享受政策
            $('.addPolicy-btn').on('click', function(){
                $('#policy-group').append(policyGroupTemp);
                handlePolicySpec();
            });
            // 删除享受政策
            $(document).find('#policy-group').on('click', '.remove-policy', function(){
                $(this).parents('.policy-div').remove();
                handlePolicySpec();
            });
            // 添加享受政策规格
            $(document).find('#policy-group').on('click', '.addPolicySpec-btn', function(){
                var specType = $(this).parents('.policySpec-div').find('.spec-type').val();
                if(specType == 0){
                    layer.msg('当前项最多只能添加一个！ ');
                    return;
                }

                $(this).parents('.policy-div').append(policySpecTemp);
                handlePolicySpec();
            });
            // 删除享受政策规格
            $(document).find('#policy-group').on('click', '.removePolicySpec-btn', function(){
                $(this).parents('.policySpec-div').remove();
                handlePolicySpec();
            });

            // 切换政策规格类型
            $(document).find('#policy-group').on('change', '.spec-type', function(){
                init_specType($(this));
            });


            // 表单提交
            $('#form-submit').on('click', function(){
                var form = this.form;
                var _this = $(this);

                if(!form.id.value) {
                    if(form.villageId.value == 0) {
                        layer.msg('请选择乡村');
                        return;
                    }
                }
                if(form.year.value.trim() == '') {
                    layer.msg('请选择台账年度');
                    form.year.focus();
                    return;
                }
                var is_policyType = true;
                $(document).find('select[name=policyType]').each(function(){
                    if($(this).val() == '0') {
                        is_policyType = false;
                    }
                });
                if(!is_policyType){
                    layer.msg('请选择享受政策');
                    return;
                }

                // 检查享受政策规格
                if(!checkPolicySpec()){
                    layer.msg('请保持每一项政策规格的分季或分月选项一致，且季度、月份值不能重复！');
                    return;
                }

                var _data = $(form).serializeObject();
                _this.prop("disabled", true);

                $.ajax({
                    url : save_url,
                    type : 'post',
                    dataType : 'json',
                    contentType : "application/json; charset=utf-8",
                    data : JSON.stringify(_data),
                }).done(function(data) {
                    _this.prop("disabled", false);
                    if (data.code == 1) {
                        layer.msg('保存成功');
                        window.location.href = data.url;
                    } else if (data.code === 0 ) {
                        layer.msg(data.msg);
                    }
                });
            });
        }

    };

}();

jQuery(document).ready(function() {
    Povertypolicyledger.init();

});
